package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 菜品管理
 *
 * @Author dml
 * Date on 2022/6/9 0009
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    // 两张表
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增成功！！");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        // 构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDotoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        // 过滤条件
        qw.like(name != null, Dish::getName, name);
        qw.orderByDesc(Dish::getUpdateTime);
        // 执行分页查询
        dishService.page(pageInfo, qw);

        // 对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDotoPage, "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            // item代表 dish表   在dish菜品表中 获取菜品id   来对应的菜系id  一个菜系id对应多个菜品id
            Long categoryId = item.getCategoryId();
            // 根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());


        dishDotoPage.setRecords(list);
        return R.success(dishDotoPage);
    }

    // 根据id查询菜品信息 口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        return R.success("修改成功！！");
    }

    /*// 套餐查询中展示  展示菜品
    @GetMapping("/list")
    public R<List<Dish>> listR(Dish dish) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        // 如果页面菜品id不为空 执行sql里面菜品id对应前端传送来的的id
        // dish.getCategoryId()前端传递  Dish::getCategoryId 后端sql中dish表只管category id表
        qw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 排序
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        // 起售状态
        qw.eq(Dish::getStatus, 1);

        List<Dish> list2 = dishService.list(qw);
        return R.success(list2);
    }*/


    // 删除以及批量删除 R
    @DeleteMapping
    public R deleteDish(@RequestParam List<Long> ids) {
        dishService.removeByIds(ids);
        System.out.println(ids);
        // TODO 完成业务逻辑
        return R.success("删除成功");
    }

    // 启用
    @PostMapping("/status/{status}")
    public R<String> updateDishStatus(@PathVariable Integer status, @RequestParam List<Long>/*long*/ ids) {
        /*for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }*/

 /*   for (Long id : ids) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishService.updateById(dish);
        }*/

        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus, status);
        qw.in(Dish::getId, ids);
        dishService.update(qw);

        return R.success("修改成功");
    }

    // category id --> 菜系  --> 菜单  --> 口味
    // 套餐查询中展示  展示菜品
    @GetMapping("/list")
    public R<List<DishDto>> listR1(Dish dish) {

        List<DishDto> dishDtos1 = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        // 从redis 缓存中获取
        dishDtos1 = (List<DishDto>)redisTemplate.opsForValue().get(key);




        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        // 如果页面菜品id不为空 执行sql里面菜品id对应前端传送来的的id
        // dish.getCategoryId()前端传递  Dish::getCategoryId 后端sql中dish表只管category id表
        qw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 排序
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        // 起售状态
        qw.eq(Dish::getStatus, 1);
        // 根据 菜单 查询 菜品
        List<Dish> list2 = dishService.list(qw);
        // 根据 菜单 查询 菜品 口味
        List<DishDto> DishDtolist = list2.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            // 分类id
            Long categoryId = item.getCategoryId();
            // 根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            // 当前菜品id
            Long dishid = item.getId();
            LambdaUpdateWrapper<DishFlavor> qw2 = new LambdaUpdateWrapper<>();
            qw2.eq(DishFlavor::getDishId,dishid);
            // 根据口味表中  dishid 查询 口味 对于菜品 N对1 菜
            List<DishFlavor> dishFlavors = dishFlavorService.list(qw2);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(DishDtolist);
    }




}
